<script setup>
import { ref, reactive, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import Card from "@/components/Card.vue";
import { coursesQueryApi } from "@/api/courses";
import { ElMessage } from "element-plus";
import { useCourseStore } from "@/store/course";
import { storeToRefs } from "pinia";
const courseStore = useCourseStore();
const { activeCourseId, searchText } = storeToRefs(courseStore);
const router = useRouter();
const route = useRoute();
const courses = ref([]);
const pageInfo = reactive({ page: 1, per_page: 12, total: 0 });
const getCourses = async () => {
  const res = await coursesQueryApi({
    type: categoryId.value,
    keyword: searchValue.value,
    page: pageInfo.page,
    per_page: pageInfo.per_page,
  });
  if (res.data.status === 200) {
    courses.value = res.data.data;
    pageInfo.total = res.data.meta.total;
  } else {
    ElMessage.error(res.data.message);
  }
};
const categoryId = computed(() => activeCourseId.value);
const searchValue = computed(() => searchText.value);
watch(
  [categoryId, searchValue],
  () => {
    getCourses();
  },
  { immediate: true }
);
const goToCourse = (id) => {
  router.push({
    path: "/course",
    query: { id, categoryId: categoryId.value },
  });
};
</script>
<template>
  <div class="page-container">
    <div class="cards row">
      <div
        class="col-md-4 col-lg-3 column"
        v-for="course of courses"
        :key="course.id"
      >
        <Card :course="course" @click="goToCourse(course.id)" />
      </div>
    </div>
    <div class="d-flex justify-content-center mb-4">
      <el-pagination
        :teleported="false"
        background
        v-model:current-page="pageInfo.page"
        v-model:page-size="pageInfo.per_page"
        :page-sizes="[12, 16, 20]"
        :total="pageInfo.total"
        layout="prev, pager, next, sizes"
        @size-change="getCourses()"
        @current-change="getCourses()"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.nav-link {
  color: rgba(0, 0, 0, 0.7);
  font-weight: 600;
  cursor: pointer;
}
.desc {
  font-size: 0.8rem;
  padding: 0.4rem;
}
.cards {
  margin-top: 2rem;
  margin-bottom: 2rem;
}
.column {
  margin-bottom: 2rem;
}
</style>
